import { ElTable, ElTableColumn } from 'element-plus';
import { PropType } from 'vue';
import './index.scss';

interface ITableColumnCommon {
  /** column 插槽 */
  vSlots?: {
    /** 自定义列的内容 The scope parameter is { row, column, $index } */
    default: () => TAnyFunction<JSX.Element | string>;
    /** 自定义表头的内容， The scope parameter is { column, $index } */
    header: () => TAnyFunction<JSX.Element | string>;
  };
  sortable?: boolean | 'custom';
}
export interface ITableColumn extends ITableColumnCommon {
  /** column key */
  label: string;
  /** 字段名称 */
  prop: string;
}
export interface ITableSelectColumn extends ITableColumnCommon {
  type: 'selection';
}

export type TTableColumn = ITableColumn | ITableSelectColumn;

export const MciTableColumn = ElTableColumn;

import { MciEmpty } from '../Empty';

export const MciTable = defineComponent({
  name: 'MciTable',
  props: {
    list: {
      type: Array as PropType<TTableColumn[]>,
      default: () => []
    },
    data: {
      type: Array,
      default: () => []
    },
    stripe: {
      type: Boolean,
      default: false
    },
    maxHeight: {
      type: Number,
      default: undefined
    },
    authCode: {
      type: String,
      default: ''
    }
  },
  setup() {
    const tableRef = ref();

    return {
      tableRef
    };
  },
  render() {
    const createTableColumns = () => {
      return this.list.map((column, index) => {
        let slots: any = null;
        if (column.vSlots) {
          const { default: slotDefault, header: slotHeader } = column.vSlots;
          slots = {
            default: slotDefault?.(),
            header: slotHeader?.()
          };
        }

        return <ElTableColumn key={index} {...column} vSlots={slots} />;
      });
    };

    const tableData = this.data;
    const emptyTipText = '暂无数据';

    return (
      <ElTable
        ref="tableRef"
        class={['mci-table']}
        data={tableData}
        maxHeight={this.maxHeight}
        tableLayout="auto"
        {...this.$attrs}
        stripe={this.stripe}>
        {{
          ...this.$slots,
          empty() {
            return (
              <div class="custom-empty my-24">
                <MciEmpty tipText={emptyTipText} />
              </div>
            );
          },
          default: () => {
            return this.$slots.default?.() || createTableColumns();
          }
        }}
      </ElTable>
    );
  }
});
